<template>
  <div id="invReaStDiv">
    <Breadcrumb content="出入库分类查询" />
    <div class="bodyContent">
      <vxe-form :data="searchForm" class="searchform form-input-m">
        <vxe-form-item title="仓库">
          <el-select v-model="searchForm.storeCode" placeholder="请选择仓库" ref="selectOrgRef" style="width:180px;" clearable @clear="clearStoreCode">
            <el-option hidden :value="searchForm.storeCode ? searchForm.storeCode : ''" :label="searchForm.storeName"></el-option>
            <el-tree filterable :data="invStoreList" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" @node-click="handleTypeNodeClick" highlight-current ref="orgTreeRef" node-key="storeCode" class="tools-tree"></el-tree>
          </el-select>
        </vxe-form-item>
        <vxe-form-item title="流转方式">
          <vxe-select v-model="searchForm.transferType" :filterable="true" @change="transferChangeEvent" clearable transfer>
            <vxe-option v-for="transfer in transTypeList" :key="transfer.id" :value="transfer.transferCode" :label="transfer.transferName"></vxe-option>
          </vxe-select>
        </vxe-form-item>
        <vxe-form-item title="调库时间[起]">
          <template #default="{ data }">
            <el-date-picker v-model="data.allotDateBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="调库时间[起]" :shortcuts="shortcuts" />
          </template>
        </vxe-form-item>
        <vxe-form-item title="调库时间[止]">
          <template #default="{ data }">
            <el-date-picker v-model="data.allotDateEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="调库时间[止]" :shortcuts="shortcuts" />
          </template>
        </vxe-form-item>
        <vxe-form-item>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="tloading" @click="findReagentStockList"></vxe-button>
        </vxe-form-item>
      </vxe-form>
      <div class="tableBox">
        <vxe-table ref="invReagentTableRef" :data="reagentStocList" :loading="tloading"  :span-method="mergeRowMethod" class="mytable-scrollbar" border align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column field="transferType" title="流转方式" ></vxe-column>
          <vxe-column field="reaNo" title="商品编号"></vxe-column>
          <vxe-column field="reaNa" title="商品名称" ></vxe-column>
          <vxe-column field="specModel" title="规格型号" ></vxe-column>
          <vxe-column field="manufacturerName" title="生产厂家" >
            <template #default="{ row }">
              <span>{{ formatCommon(invManufacturerList, row.manufacturerNo) }}</span>
            </template>
          </vxe-column>
          <vxe-column field="applyNum" title="调拨数量"></vxe-column>
          <vxe-column field="unit" title="单位"></vxe-column>
          <vxe-column field="costPrice" title="单价"></vxe-column>
          <vxe-column field="costs" title="金额"></vxe-column>
        </vxe-table>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import moment from 'moment';
import {AppStore} from "@/stores/store";

// 全局变量定义区 ==========
let store = AppStore();

let searchForm = reactive({
  allotDateBegin: moment().format('YYYY-MM-DD HH:mm:ss'),
  allotDateEnd: moment().format('YYYY-MM-DD HH:mm:ss'),
  transferType:'',
  storeCode: (!isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeCode))?store.curInvStoreObj.storeCode:'',
  storeName: (!isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeName))?store.curInvStoreObj.storeName:''
});

let defaultProps = {
  children: 'children',
  label: 'storeName'
};
let tloading = ref(false); //刷新加载状态
let reagentStocList: any = reactive([]);
let invManufacturerList: any = reactive([]);
let invOrderStatusList: any = reactive([]);
let transTypeList: any = reactive([]);
let invStoreList: any = reactive([]);


// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findInvManufacturerList();
  getDictItemsList(); //批量获取字典
  findReagentStockList();
  findInvTransTypeList();
  findStoreManageTree();
});
async function findInvTransTypeList() {
  const url = '/inv/transfer/type/findInvTransferTypeList';
  await proxy.$http
      //注意此处的数据条数
      .get(url, { params: { businessType: '01,02', showFlag: true } })
      .then((res: any) => {
        if (res.status.code === 1) {
          transTypeList.push(...res.data);
        }
      })
      .catch((err: any) => {
        // VxeMessage('获取机构列表失败',VxeNotifyType.error)
      });
}
function findStoreManageTree() {
  invStoreList.length = 0;

  const url = '/inv/storeManage/findStoreManageTree';
  proxy.$http
      .get(url)
      .then((res: any) => {
        if (res.status.code !== 1) {
          proxy.$alert(res.status.msg, '提示');
        } else {
          invStoreList.push(...res.data.invStoreTree);
          if (!isEmpty(searchForm.storeCode)){
            setCurOrgTreeNode(searchForm.storeCode);
          }
        }
      })
      .catch((err: any) => {
        VxeMessage('获取机构失败', VxeNotifyType.error);
      });
}
// 光标定位在指定字典分类上
function setCurOrgTreeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'orgTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['invOrderStatus'];

  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });

  const iosObj = dictTreeTypeItems.data.find((item: any) => item.code === 'invOrderStatus');
  invOrderStatusList.push(...iosObj.detailDataList);
}
function findInvManufacturerList(){
  invManufacturerList.length = 0; //放入数据前清空数据
  const url = '/lis/inv/manufacturer/findInvManufacturerList';
  proxy.$http
      //注意此处的数据条数
      .get(url)
      .then((res: any) => {
        invManufacturerList.push(...res.data);
      })
      .catch((err: any) => {
      });
}
function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.manuCode == value) {
      return item.manuName;
    }
  }
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReagentStockList();
  }
}
function findReagentStockList() {
  tloading.value = true;
  reagentStocList.length = 0; //放入数据前清空数据
  const url = '/inv/orderReagent/findOrderReagentByTransferType';
  proxy.$http
      //注意此处的数据条数
      .get(url, {params:searchForm})
      .then((res: any) => {
        reagentStocList.push(...res.data);
        tloading.value = false;
      })
      .catch((err: any) => {
        tloading.value = false;
        // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
      });
}

function mergeRowMethod({ row, _rowIndex, column, visibleData }) {
  const fields = ['reaNo', 'reaNa'];
  const cellValue = row[column.field];
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
}
</script>

<style lang="scss" scoped>
#invReaStDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .button-red {
      margin: 5px 0 5px 5px;
    }
    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }

    .tableBox {
      height: calc(100% - 40px);
      background-color: $base-white;
    }

    .el-tabs {
      height: 100%;
      // 右侧保存按钮
      .saveBtn {
        margin: 0px 30px;
      }
    }
  }
}
</style>
